﻿CREATE PROCEDURE [ServiceEngine].[DeleteOperation]
@ID UNIQUEIDENTIFIER
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	SET NOCOUNT ON;

	BEGIN TRY
		BEGIN TRANSACTION

		-- Delete All Related MessageParts
		DELETE 
			ServiceEngine.MessageParts
		FROM
			ServiceEngine.MessageParts MP JOIN ServiceEngine.OperationVersions OV ON MP.OperationVersionID = OV.OperationVersionID
		WHERE
			OV.OperationID = @ID
			 
		-- Delete All Related MessageHeaders
		DELETE 
			ServiceEngine.MessageHeaders
		FROM
			ServiceEngine.MessageHeaders MH JOIN ServiceEngine.OperationVersions OV ON MH.OperationVersionID = OV.OperationVersionID
		WHERE
			OV.OperationID = @ID
			 
		-- Delete All Related MessageFaults
		DELETE 
			ServiceEngine.SoapFaults
		FROM
			ServiceEngine.SoapFaults SF JOIN ServiceEngine.OperationVersions OV ON SF.OperationVersionID = OV.OperationVersionID
		WHERE
			OV.OperationID = @ID
			 
		-- Delete All Related OperationVersion
		DELETE	OperationVersions
		WHERE	OperationID = @ID

		DELETE	ServiceEngine.Operations 
		WHERE	OperationID = @ID

		DELETE	ServiceEngine.Names
		WHERE	EntityID = @ID and EntityTypeID = 4

		COMMIT TRANSACTION
	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH
END

